import Taro from '@tarojs/taro'
import { API_CONFIG, DEV_CONFIG } from '../config/api'
import cityCodesData from '../static/tableConvert.com_kvjxnh.json'

// 城市编码数据接口
interface CityCodeData {
  中文名: string
  adcode: string
  citycode: string
}

// 高德天气API响应接口
export interface AmapWeatherResponse {
  status: string
  count: string
  info: string
  infocode: string
  lives: Array<{
    province: string
    city: string
    adcode: string
    weather: string
    temperature: string
    winddirection: string
    windpower: string
    humidity: string
    reporttime: string
    temperature_float: string
    humidity_float: string
  }>
}

// 统一的天气数据接口（保持与现有组件兼容）
export interface WeatherApiResponse {
  city: string
  province?: string
  temperature: number
  weather: string
  windDirection?: string
  windPower?: number
  humidity?: string
}

export interface WeatherApiError {
  status: string
  info: string
  infocode: string
}

// 高德天气API配置
const AMAP_WEATHER_CONFIG = {
  baseUrl: API_CONFIG.amap.weatherApiUrl,
  apiKey: API_CONFIG.amap.apiKey,
  extensions: 'base' // 获取实况天气
}

// 城市编码数据（从JSON文件加载）
const cityCodes: CityCodeData[] = cityCodesData as CityCodeData[]

// 创建城市名称到adcode的映射表（优化查询性能）
const createCityCodeMap = (): Record<string, string> => {
  const map: Record<string, string> = {}
  
  cityCodes.forEach(city => {
    const cityName = city.中文名
    const adcode = city.adcode
    
    // 添加完整名称映射
    map[cityName] = adcode
    
    // 添加不带"市"、"县"、"区"后缀的映射
    const cleanName = cityName.replace(/[市县区]$/, '')
    if (cleanName !== cityName) {
      map[cleanName] = adcode
    }
    
    // 特殊处理：为直辖市和重要城市添加简化名称
    if (cityName === '北京市') {
      map['北京'] = adcode
      map['北京城区'] = adcode
    } else if (cityName === '上海市') {
      map['上海'] = adcode
      map['上海城区'] = adcode
    } else if (cityName === '天津市') {
      map['天津'] = adcode
      map['天津城区'] = adcode
    } else if (cityName === '重庆市') {
      map['重庆'] = adcode
      map['重庆城区'] = adcode
    }
  })
  
  return map
}

const CITY_CODE_MAP = createCityCodeMap()


/**
 * 获取城市编码（adcode）
 * @param cityName 城市名称
 * @returns 城市编码
 */
export const getCityCode = (cityName: string): string | null => {
  // 输入验证
  if (!cityName || typeof cityName !== 'string') {
    return null
  }
  
  const trimmedCityName = cityName.trim()
  if (!trimmedCityName) {
    return null
  }
  
  console.log('=== 城市编码匹配过程 ===')
  console.log('输入城市名称:', trimmedCityName)
  
  // 1. 直接精确匹配（使用预构建的映射表）
  if (CITY_CODE_MAP[trimmedCityName]) {
    console.log('精确匹配成功:', trimmedCityName, '->', CITY_CODE_MAP[trimmedCityName])
    return CITY_CODE_MAP[trimmedCityName]
  }
  
  // 2. 智能匹配 - 处理省+市+区的完整结构
  // 首先处理完整的"省+市+区"格式，如"浙江省杭州市临安区"或"浙江杭州市临安区"
  const provinceCityDistrictPattern = /^(.+省)(.+市)(.+区)$/
  const provinceMatch = trimmedCityName.match(provinceCityDistrictPattern)
  
  if (provinceMatch && provinceMatch.length === 4) {
    const provincePart = provinceMatch[1].trim() // 如"浙江省"
    const cityPart = provinceMatch[2].trim() // 如"杭州市"
    const districtPart = provinceMatch[3].trim() // 如"临安区"
    
    console.log('尝试省+市+区组合匹配:', provincePart, '+', cityPart, '+', districtPart)
    
    // 第一步：找到城市的citycode
    const cityMatch = cityCodes.find(city => city.中文名 === cityPart)
    if (cityMatch && cityMatch.citycode !== '\\N') {
      const cityCode = cityMatch.citycode
      console.log('找到城市citycode:', cityPart, '->', cityCode)
      
      // 第二步：在该citycode下查找区县
      const districtMatch = cityCodes.find(city => 
        city.中文名 === districtPart && city.citycode === cityCode
      )
      
      if (districtMatch) {
        console.log('省+市+区组合匹配成功:', districtMatch.中文名, '->', districtMatch.adcode)
        return districtMatch.adcode
      }
    }
  }
  
  // 处理没有"省"字的省+市+区格式，如"浙江杭州市临安区"
  const provinceCityDistrictPatternNoProvince = /^(.+)(.+市)(.+区)$/
  const provinceMatchNoProvince = trimmedCityName.match(provinceCityDistrictPatternNoProvince)
  
  if (provinceMatchNoProvince && provinceMatchNoProvince.length === 4) {
    const provincePart = provinceMatchNoProvince[1].trim() // 如"浙江"
    const cityPart = provinceMatchNoProvince[2].trim() // 如"杭州市"
    const districtPart = provinceMatchNoProvince[3].trim() // 如"临安区"
    
    console.log('尝试无省字省+市+区组合匹配:', provincePart, '+', cityPart, '+', districtPart)
    
    // 第一步：找到城市的citycode
    const cityMatch = cityCodes.find(city => city.中文名 === cityPart)
    if (cityMatch && cityMatch.citycode !== '\\N') {
      const cityCode = cityMatch.citycode
      console.log('找到城市citycode:', cityPart, '->', cityCode)
      
      // 第二步：在该citycode下查找区县
      const districtMatch = cityCodes.find(city => 
        city.中文名 === districtPart && city.citycode === cityCode
      )
      
      if (districtMatch) {
        console.log('无省字省+市+区组合匹配成功:', districtMatch.中文名, '->', districtMatch.adcode)
        return districtMatch.adcode
      }
    }
  }
  
  // 4. 处理完整的"市+区"格式，如"北京市朝阳区"
  const fullCityDistrictPattern = /^(.+市)(.+区)$/
  const fullMatch = trimmedCityName.match(fullCityDistrictPattern)
  
  if (fullMatch && fullMatch.length === 3) {
    const cityPart = fullMatch[1].trim() // 如"北京市"
    const districtPart = fullMatch[2].trim() // 如"朝阳区"
    
    console.log('尝试完整市+区组合匹配:', cityPart, '+', districtPart)
    
    // 第一步：找到城市的citycode
    const cityMatch = cityCodes.find(city => city.中文名 === cityPart)
    if (cityMatch && cityMatch.citycode !== '\\N') {
      const cityCode = cityMatch.citycode
      console.log('找到城市citycode:', cityPart, '->', cityCode)
      
      // 第二步：在该citycode下查找区县
      const districtMatch = cityCodes.find(city => 
        city.中文名 === districtPart && city.citycode === cityCode
      )
      
      if (districtMatch) {
        console.log('完整市+区组合匹配成功:', districtMatch.中文名, '->', districtMatch.adcode)
        return districtMatch.adcode
      }
    }
  }
  
  // 5. 处理省+市+区的简化格式，如"浙江杭州临安"
  const simpleProvinceCityDistrictPattern = /^(.+省)(.+市)(.+)$/
  const simpleProvinceMatch = trimmedCityName.match(simpleProvinceCityDistrictPattern)
  
  if (simpleProvinceMatch && simpleProvinceMatch.length === 4) {
    const provincePart = simpleProvinceMatch[1].trim() // 如"浙江省"
    const cityPart = simpleProvinceMatch[2].trim() // 如"杭州市"
    const districtPart = simpleProvinceMatch[3].trim() // 如"临安"
    
    console.log('尝试简化省+市+区组合匹配:', provincePart, '+', cityPart, '+', districtPart)
    
    // 第一步：找到城市的citycode
    const cityMatch = cityCodes.find(city => city.中文名 === cityPart)
    if (cityMatch && cityMatch.citycode !== '\\N') {
      const cityCode = cityMatch.citycode
      console.log('找到城市citycode:', cityPart, '->', cityCode)
      
      // 第二步：在该citycode下查找区县
      const districtMatch = cityCodes.find(city => {
        const districtName = city.中文名
        return (districtName === districtPart + '区' || districtName.includes(districtPart)) &&
               city.citycode === cityCode
      })
      
      if (districtMatch) {
        console.log('简化省+市+区组合匹配成功:', districtMatch.中文名, '->', districtMatch.adcode)
        return districtMatch.adcode
      }
    }
  }
  
  // 6. 处理简化的"市+区"格式，如"北京朝阳"、"上海浦东"、"杭州临安"
  const commonDistricts = ['朝阳', '海淀', '丰台', '石景山', '东城', '西城', '门头沟', '房山', '通州', '顺义', '昌平', '大兴', '怀柔', '平谷', '密云', '延庆', '浦东', '黄浦', '徐汇', '长宁', '静安', '普陀', '虹口', '杨浦', '闵行', '宝山', '嘉定', '金山', '松江', '青浦', '奉贤', '崇明', '天河', '越秀', '荔湾', '海珠', '白云', '黄埔', '番禺', '花都', '南沙', '从化', '增城', '临安', '萧山', '余杭', '富阳', '临平', '桐庐', '淳安', '建德']
  
  // 检查是否包含常见的区县名称
  const matchedDistrict = commonDistricts.find(district => 
    trimmedCityName.includes(district) && trimmedCityName.length > district.length
  )
  
  if (matchedDistrict) {
    const potentialCity = trimmedCityName.replace(matchedDistrict, '').trim()
    console.log('尝试简化市+区组合匹配:', potentialCity, '+', matchedDistrict)
    
    // 第一步：找到城市的citycode
    const cityCandidates = cityCodes.filter(city => {
      const cityName = city.中文名
      return cityName === potentialCity || 
             cityName === potentialCity + '市' ||
             cityName.replace(/市$/, '') === potentialCity
    })
    
    // 如果找不到对应的城市，跳过这个匹配逻辑
    if (cityCandidates.length === 0) {
      console.log('简化市+区组合匹配失败：未找到对应城市', potentialCity)
    } else {
      for (const cityCandidate of cityCandidates) {
        if (cityCandidate.citycode !== '\\N') {
          const cityCode = cityCandidate.citycode
          console.log('找到候选城市citycode:', cityCandidate.中文名, '->', cityCode)
          
          // 第二步：在该citycode下查找区县，优先匹配精确名称
          let districtMatch = cityCodes.find(city => {
            const districtName = city.中文名
            return districtName === matchedDistrict + '区' && city.citycode === cityCode
          })
          
          // 如果没找到精确匹配，再查找包含匹配
          if (!districtMatch) {
            districtMatch = cityCodes.find(city => {
              const districtName = city.中文名
              return districtName.includes(matchedDistrict) && city.citycode === cityCode
            })
          }
          
          if (districtMatch) {
            console.log('简化市+区组合匹配成功:', districtMatch.中文名, '->', districtMatch.adcode)
            return districtMatch.adcode
          }
        }
      }
    }
  }
  
  // 7. 模糊匹配 - 去除常见后缀
  const cleanCityName = trimmedCityName.replace(/[市县区]$/, '')
  if (cleanCityName !== trimmedCityName && CITY_CODE_MAP[cleanCityName]) {
    console.log('模糊匹配成功（去除后缀）:', cleanCityName, '->', CITY_CODE_MAP[cleanCityName])
    return CITY_CODE_MAP[cleanCityName]
  }
  
  // 8. 智能匹配 - 处理特殊情况
  // 处理"北京城区" -> "北京"的情况
  if (trimmedCityName.includes('城区')) {
    const baseCity = trimmedCityName.replace('城区', '')
    if (CITY_CODE_MAP[baseCity]) {
      console.log('智能匹配成功（城区）:', baseCity, '->', CITY_CODE_MAP[baseCity])
      return CITY_CODE_MAP[baseCity]
    }
  }
  
  // 9. 在JSON数据中直接搜索（支持更复杂的匹配）
  // 优先匹配更重要的城市（直辖市、省会等）
  const directMatches = cityCodes.filter(city => {
    const fullName = city.中文名
    const shortName = fullName.replace(/[市县区]$/, '')
    
    return fullName === trimmedCityName || 
           shortName === trimmedCityName ||
           fullName.includes(trimmedCityName) ||
           trimmedCityName.includes(shortName)
  })
  
  if (directMatches.length > 0) {
    // 如果有多个匹配，优先选择区县级别（更精确）
    const districtMatches = directMatches.filter(city => 
      city.中文名.includes('区') || city.中文名.includes('县')
    )
    
    if (districtMatches.length > 0) {
      // 优先选择区县级别的匹配，并考虑地理位置相关性
      const prioritizedMatch = prioritizeCityMatch(districtMatches, trimmedCityName)
      console.log('JSON数据匹配成功（区县优先）:', prioritizedMatch.中文名, '->', prioritizedMatch.adcode)
      return prioritizedMatch.adcode
    } else {
      // 如果没有区县匹配，选择市级匹配
      const prioritizedMatch = prioritizeCityMatch(directMatches, trimmedCityName)
      console.log('JSON数据匹配成功:', prioritizedMatch.中文名, '->', prioritizedMatch.adcode)
      return prioritizedMatch.adcode
    }
  }
  
  // 10. 模糊搜索 - 包含匹配
  const matchedEntry = Object.entries(CITY_CODE_MAP).find(([key]) => 
    key.includes(trimmedCityName) || trimmedCityName.includes(key)
  )
  
  if (matchedEntry) {
    console.log('模糊搜索成功:', matchedEntry[0], '->', matchedEntry[1])
    return matchedEntry[1]
  }
  
  console.log('城市编码匹配失败:', trimmedCityName)
  console.log('可用城市示例:', Object.keys(CITY_CODE_MAP).slice(0, 10))
  return null
}

/**
 * 城市匹配优先级排序
 * 优先匹配直辖市、省会城市等更重要的城市，并考虑地理位置相关性
 */
const prioritizeCityMatch = (matches: CityCodeData[], queryString?: string): CityCodeData => {
  // 优先级权重
  const getPriority = (cityName: string): number => {
    // 直辖市
    if (cityName.includes('北京') || cityName.includes('上海') || 
        cityName.includes('天津') || cityName.includes('重庆')) {
      return 100
    }
    
    // 省会城市（简化判断）
    const provincialCapitals = ['广州', '杭州', '南京', '成都', '武汉', '西安', '济南', '长沙', '郑州', '石家庄', '太原', '呼和浩特', '沈阳', '长春', '哈尔滨', '合肥', '南昌', '昆明', '贵阳', '兰州', '银川', '西宁', '乌鲁木齐', '拉萨', '海口']
    
    if (provincialCapitals.some(capital => cityName.includes(capital))) {
      return 80
    }
    
    // 重要地级市
    const importantCities = ['苏州', '青岛', '大连', '厦门', '宁波', '福州', '深圳']
    if (importantCities.some(city => cityName.includes(city))) {
      return 60
    }
    
    // 区县级别
    if (cityName.includes('区') || cityName.includes('县')) {
      return 40
    }
    
    // 其他城市
    return 20
  }

  // 地理位置相关性权重
  const getLocationRelevance = (cityName: string, query: string): number => {
    if (!query) return 0
    
    let relevance = 0
    
    // 提取查询中的省、市信息
    const provinces = ['北京', '天津', '上海', '重庆', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西', '海南', '四川', '贵州', '云南', '西藏', '陕西', '甘肃', '青海', '宁夏', '新疆']
    const cities = ['北京', '天津', '上海', '重庆', '石家庄', '太原', '呼和浩特', '沈阳', '长春', '哈尔滨', '南京', '杭州', '合肥', '福州', '南昌', '济南', '郑州', '武汉', '长沙', '广州', '南宁', '海口', '成都', '贵阳', '昆明', '拉萨', '西安', '兰州', '西宁', '银川', '乌鲁木齐']
    
    // 检查查询中是否包含省份信息
    const matchedProvince = provinces.find(province => query.includes(province))
    if (matchedProvince) {
      // 省份与主要城市的映射关系
      const provinceToCapital = {
        '浙江': '杭州',
        '江苏': '南京', 
        '广东': '广州',
        '山东': '济南',
        '河南': '郑州',
        '湖北': '武汉',
        '湖南': '长沙',
        '四川': '成都',
        '陕西': '西安',
        '辽宁': '沈阳',
        '吉林': '长春',
        '黑龙江': '哈尔滨',
        '安徽': '合肥',
        '福建': '福州',
        '江西': '南昌',
        '河北': '石家庄',
        '山西': '太原',
        '内蒙古': '呼和浩特',
        '广西': '南宁',
        '海南': '海口',
        '贵州': '贵阳',
        '云南': '昆明',
        '西藏': '拉萨',
        '甘肃': '兰州',
        '青海': '西宁',
        '宁夏': '银川',
        '新疆': '乌鲁木齐'
      }
      
      const capitalCity = provinceToCapital[matchedProvince]
      
      // 如果城市名称包含该省份的主要城市，增加相关性
      if (capitalCity && cityName.includes(capitalCity)) {
        relevance += 30
      } else if (capitalCity) {
        // 通过citycode间接关联：查找该省份主要城市的citycode，然后检查候选城市是否共享相同citycode
        const capitalMatch = cityCodes.find(c => c.中文名.includes(capitalCity) && c.citycode !== '\\N')
        if (capitalMatch) {
          const capitalCityCode = capitalMatch.citycode
          const currentCity = cityCodes.find(c => c.中文名 === cityName)
          if (currentCity && currentCity.citycode === capitalCityCode) {
            relevance += 25 // 通过省份间接关联的分值
          }
        }
      }
    }
    
    // 检查查询中是否包含城市信息，并考虑citycode关系
    const matchedCity = cities.find(city => query.includes(city))
    if (matchedCity) {
      // 直接匹配城市名
      if (cityName.includes(matchedCity)) {
        relevance += 50
      } else {
        // 通过citycode间接匹配（区县与主城市的关联）
        const cityMatch = cityCodes.find(c => c.中文名.includes(matchedCity) && c.citycode !== '\\N')
        if (cityMatch) {
          const targetCityCode = cityMatch.citycode
          const currentCity = cityCodes.find(c => c.中文名 === cityName)
          if (currentCity && currentCity.citycode === targetCityCode) {
            relevance += 40 // 间接关联的分值稍低
          }
        }
      }
    }
    
    return relevance
  }
  
  // 按优先级和地理位置相关性排序，返回优先级最高的
  return matches.sort((a, b) => {
    const priorityA = getPriority(a.中文名)
    const priorityB = getPriority(b.中文名)
    
    // 如果优先级相同，比较地理位置相关性
    if (priorityA === priorityB) {
      const relevanceA = getLocationRelevance(a.中文名, queryString || '')
      const relevanceB = getLocationRelevance(b.中文名, queryString || '')
      return relevanceB - relevanceA
    }
    
    return priorityB - priorityA
  })[0]
}

/**
 * 获取城市天气信息
 * @param cityName 城市名称
 * @returns Promise<WeatherApiResponse>
 */
export const fetchWeatherByCity = async (cityName: string): Promise<WeatherApiResponse> => {
  // 如果配置为使用模拟数据，直接返回模拟数据
  if (DEV_CONFIG.useMockData) {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, DEV_CONFIG.mockDelay))
    return getMockWeatherData(cityName)
  }

  // 检查API密钥是否已配置
  if (AMAP_WEATHER_CONFIG.apiKey === 'your_amap_key_here') {
    throw new Error('请先在 src/config/api.ts 中配置高德API密钥')
  }

  // 获取城市编码
  const cityCode = getCityCode(cityName)
  if (!cityCode) {
    throw new Error(`暂不支持城市"${cityName}"，请尝试其他城市`)
  }

  const url = AMAP_WEATHER_CONFIG.baseUrl
  const params = {
    key: AMAP_WEATHER_CONFIG.apiKey,
    city: cityCode,
    extensions: AMAP_WEATHER_CONFIG.extensions
  }

  try {
    const response = await Taro.request({
      url,
      method: 'GET',
      data: params,
      header: {
        'Content-Type': 'application/json'
      }
    })

    if (response.statusCode !== 200) {
      throw new Error(`HTTP ${response.statusCode}: 请求失败`)
    }

    const data = response.data as AmapWeatherResponse

    // 检查API响应状态
    if (data.status !== '1' || data.infocode !== '10000') {
      throw new Error(data.info || '获取天气信息失败')
    }

    // 检查是否有天气数据
    if (!data.lives || data.lives.length === 0) {
      throw new Error('未获取到天气数据')
    }

    const weatherInfo = data.lives[0]
    
    // 转换为统一格式
    const result = {
      city: weatherInfo.city,
      province: weatherInfo.province,
      temperature: parseInt(weatherInfo.temperature),
      weather: weatherInfo.weather,
      windDirection: weatherInfo.winddirection,
      windPower: parseWindPower(weatherInfo.windpower),
      humidity: weatherInfo.humidity
    }
    
    console.log('天气数据获取成功:', result.city, result.weather, result.temperature + '°C')
    
    return result
  } catch (error) {
    if (error instanceof Error) {
      throw error
    }
    throw new Error('网络请求失败，请检查网络连接')
  }
}

/**
 * 解析风力级别
 * @param windPower 风力描述
 * @returns 风力级别数字
 */
const parseWindPower = (windPower: string): number | undefined => {
  // 处理风力描述，如"≤3"、"4-5"等
  if (windPower.includes('≤')) {
    return parseInt(windPower.replace('≤', ''))
  }
  if (windPower.includes('-')) {
    const [min] = windPower.split('-')
    return parseInt(min)
  }
  const num = parseInt(windPower)
  return isNaN(num) ? undefined : num
}


/**
 * 模拟天气数据（开发阶段使用）
 * @param cityName 城市名称
 * @returns 模拟的天气数据
 */
export const getMockWeatherData = (cityName: string): WeatherApiResponse => {
  const weatherTypes = ['晴', '多云', '小雨', '阴', '雷阵雨', '雾', '霾']
  const windDirections = ['北风', '东北风', '东风', '东南风', '南风', '西南风', '西风', '西北风']
  
  const randomWeather = weatherTypes[Math.floor(Math.random() * weatherTypes.length)]
  const randomWindDirection = windDirections[Math.floor(Math.random() * windDirections.length)]

  return {
    city: cityName,
    province: '模拟省份',
    temperature: Math.round(Math.random() * 30 + 5), // 5-35度
    weather: randomWeather,
    windDirection: randomWindDirection,
    windPower: Math.round(Math.random() * 6 + 1), // 1-6级
    humidity: `${Math.round(Math.random() * 50 + 30)}` // 30-80%
  }
}
